/*
 *
 * Copyright (c) 2020-2022, Java知识图谱 (http://www.altitude.xin).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package xin.altitude.db.redis.sync.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.altitude.cms.common.util.RedisUtils;
import xin.altitude.db.redis.sync.domain.BuOrder;
import xin.altitude.db.redis.sync.mapper.OrderMapper;
import xin.altitude.db.redis.sync.service.IOrderService2;

import java.util.concurrent.TimeUnit;

/**
 * @author explore
 * @since 2022/03/04 19:07
 **/
@Service
public class OrderServiceImpl2 extends ServiceImpl<OrderMapper, BuOrder> implements IOrderService2 {
    public static final String ORDER_KEY_PREFIX = "ORDER_KEY_PREFIX::";
    public static final String ORDER_LOCK = "order_lock::";
    
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    /**
     * 编辑订单
     *
     * @param order
     * @return
     */
    @Override
    public Boolean editOrder(BuOrder order) {
        /* 更新数据库 */
        updateById(order);
        /* 删除缓存 */
        RedisUtils.deleteObject(OrderServiceImpl.ORDER_KEY_PREFIX + order.getOrderId());
        return true;
    }
    
    /**
     * 查询订单详情
     *
     * @param orderId 订单ID
     * @return BuOrder
     */
    @Override
    public BuOrder getOrder(Long orderId) {
        String key = ORDER_KEY_PREFIX + orderId;
        BuOrder buOrder = RedisUtils.getObject(key, BuOrder.class);
        if (buOrder != null) {
            return buOrder;
        }
        BuOrder order = getById(orderId);
        /* 此处建议使用异步，缩短响应时间 */
        RedisUtils.setObject(key, order, 5, TimeUnit.MINUTES);
        return order;
    }
}
